/**
 * 
 */
package org.zp.study.core.controller;

import com.baomidou.mybatisplus.plugins.Page;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.zp.study.core.base.BaseModel;
import org.zp.study.core.base.Bean;
import org.zp.study.core.base.Parameter;
import org.zp.study.core.base.Result;
import org.zp.study.core.provider.BaseProvider;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 控制器基类
 * 如果用提供器来调服务，继承此类
 * @author zhaopan
 * @version 2016年5月20日 下午3:47:58
 */
public abstract class AbstractController<T extends BaseProvider> extends BaseController {
	protected final Logger logger = LogManager.getLogger(this.getClass());
	@Autowired
	protected T executor;

	public abstract String getService();
	/**
	 * 分页查询
	 */
	public Object queryPage(ModelMap modelMap, Map<String, Object> param,String method) {
		Parameter parameter = new Parameter(getService(), method).setMap(param);
		Page<?> list = executor.execute(parameter).getPage();
		return setResponseCode(modelMap, list);
	}
	/**
	 * 列表查询
	 */
	public Object queryList(ModelMap modelMap, Map<String, Object> param,String method) {
		Parameter parameter = new Parameter(getService(),method).setMap(param);
		List<?> list = executor.execute(parameter).getList();
		return setResponseCode(modelMap, list);
	}

	/**
	 * 通过id查询，返回BaseModel
	 */
	public Object getById(ModelMap modelMap, BaseModel param,String method) {
		Parameter parameter = new Parameter(getService(), method).setId(param.getId());
		Bean result = executor.execute(parameter).getModel();
		return setResponseCode(modelMap, result);
	}

	/**
	 * 更新
	 * @param modelMap
	 * @param param
	 * @return
	 */
	public Object update(ModelMap modelMap, BaseModel param,String method) {
		Long userId = getCurrUser();
		if (param.getId() == null) {
			param.setCreateBy(userId);
			param.setCreateTime(new Date());
		}
		param.setUpdateBy(userId);
		param.setUpdateTime(new Date());
		Parameter parameter = new Parameter(getService(), method).setModel(param);
		executor.execute(parameter);
		return setResponseSuccessCode(modelMap);
	}

	/**
	 * 删除
	 * @param modelMap
	 * @param param
	 * @return
	 */
	public Object delete(ModelMap modelMap, BaseModel param,String method) {
		Parameter parameter = new Parameter(getService(),method).setId(param.getId());
		executor.execute(parameter);
		return setResponseSuccessCode(modelMap);
	}

	/**
	 * 通用方法
	 * @param modelMap
	 * @param method
	 * @return
	 */
	public Object Universal(ModelMap modelMap,Object object, String method){
		Parameter parameter = new Parameter(getService(),method).setObject(object);
		Result result=executor.execute(parameter);
		return setResponseCode(modelMap,result);
	}
}